<?php

namespace app\api\controller\order;

use app\api\model\order\Cart as CartModel;
use app\api\model\order\Order as OrderModel;
use app\api\service\order\settled\MasterOrderSettledService;
use app\api\controller\Controller;
use app\api\model\settings\Message as MessageModel;
use app\api\model\settings\Setting as SettingModel;
use app\api\service\points\PointsDeductService;
use app\api\validate\order\OrderValidate;
use app\common\enum\order\OrderPayStatusEnum;
use app\common\enum\order\OrderSourceEnum;
use app\common\model\plus\point\PointProduct;

/**
 * 普通订单
 */
class Order extends Controller
{
    /**
     * 订单确认-立即购买
     */
    public function buy()
    {
        //try {
        // 立即购买：获取订单商品列表
        $params = $this->postData();
        validate(OrderValidate::class)->scene('buy')->check($params);
        $products = OrderModel::getOrderProductListByNow($params);
        $user = $this->getUser();
        // 实例化订单service
        $orderService = new MasterOrderSettledService($user, $products, $params);
        // 获取订单信息
        $orderInfo = $orderService->settlement();
        // 订单结算提交
        if ($orderService->hasError()) {
            return $this->renderError($orderService->getError());
        }
        if ($this->request->isGet()) {
            // 如果来源是小程序, 则获取小程序订阅消息id.获取支付成功,发货通知.
            $template_arr = MessageModel::getMessageByNameArr($params['pay_source'], ['order_pay_user', 'order_delivery_user']);
            //是否显示店铺信息
            $store_open = SettingModel::getStoreOpen();
            $balance = $user['balance'];
            return $this->renderSuccess('', compact('orderInfo', 'template_arr', 'store_open', 'balance'));
        }
        // 创建订单
        $order_id = $orderService->createOrder($orderInfo);
        if (!$order_id) {
            return $this->renderError($orderService->getError() ?: '订单创建失败');
        }
        // 返回订单信息
        return $this->renderSuccess('', [
            'order_id' => $order_id,   // 订单号
        ]);
        /*} catch (\Exception $e) {
            return $this->renderError($e->getMessage());
        }*/
    }

    /**
     * 购物车购买
     */
    public function cart()
    {
        // 立即购买：获取订单商品列表
        $params = $this->postData();
        $params['pay_source'] = $params['pay_source'] ?? "wx";
        $user = $this->getUser();
        // 商品结算信息
        $CartModel = new CartModel();
        // 购物车商品列表
        $supplierData = $CartModel->getList($user, $params['cart_ids']);
        // 实例化订单service
        $orderService = new MasterOrderSettledService($user, $supplierData, $params);
        // 获取订单信息
        $orderInfo = $orderService->settlement();
        if ($this->request->isGet()) {
            // 如果来源是小程序, 则获取小程序订阅消息id.获取支付成功,发货通知.
            $template_arr = MessageModel::getMessageByNameArr($params['pay_source'], ['order_pay_user', 'order_delivery_user']);
            //是否显示店铺信息
            $store_open = SettingModel::getStoreOpen();
            $balance = $user['balance'];
            return $this->renderSuccess('', compact('orderInfo', 'template_arr', 'store_open', 'balance'));
        }
        // 订单结算提交
        if ($orderService->hasError()) {
            return $this->renderError($orderService->getError());
        }
        // 创建订单
        $order_id = $orderService->createOrder($orderInfo);
        if (!$order_id) {
            return $this->renderError($orderService->getError() ?: '订单创建失败');
        }
        // 移出购物车中已下单的商品
        $CartModel->clearAll($user, $params['cart_ids']);
        // 返回订单信息
        return $this->renderSuccess('', [
            'order_id' => $order_id,   // 订单号
        ]);
    }

    /**
     * 订单确认-立即购买
     */
    public function pointBuy()
    {
        try {
            // 立即购买：获取订单商品列表
            $params = $this->postData();
            validate(OrderValidate::class)->scene('buy')->check($params);
            $product_id = $params['product_id'];
            //是否是积分商品
            $point_product = PointProduct::where('product_id', $product_id)->find();
            if(!$point_product){
                return $this->renderError('该商品未开启兑换');
            }
            $point_price = $point_product['point_price'];
            $user = $this->getUser();
            $point_ratio = PointsDeductService::getPointRatio($user);
            $points = 0;
            if ($point_ratio > 0) {
                $points = ceil($point_price / $point_ratio);
                if ($points > $user['points']) {
                    $setting = SettingModel::getItem('points');
                    $point_name = $setting['points_name']??'积分';
                    return $this->renderError($point_name.'不足');
                }
            } else {
                return $this->renderError('系统未开启兑换功能');
            }
            
            $products = OrderModel::getOrderProductListByNow($params);
            foreach ($products[0]['productList'] as &$product) {
                $product['product_price'] = $point_price;
                $product['points_money'] = $point_price;
                $product['points_num'] = $points;
            }
            // 实例化订单service
            $orderService = new MasterOrderSettledService($user, $products, $params);
            // 获取订单信息
            $orderInfo = $orderService->settlement();
            // 订单结算提交
            if ($orderService->hasError()) {
                return $this->renderError($orderService->getError());
            }
            $orderInfo['orderData']['force_points'] = 1;
            $orderInfo['orderData']['points_money'] = $point_price;
            $orderInfo['orderData']['points_num'] = $points;
            $orderInfo['orderData']['order_source'] = OrderSourceEnum::POINT;
            // 创建订单
            $order_id = $orderService->createOrder($orderInfo);
            if (!$order_id) {
                return $this->renderError($orderService->getError() ?: '订单创建失败');
            }
            $order = OrderModel::find($order_id);
            //设为已支付
            $order->save(['pay_status' => OrderPayStatusEnum::SUCCESS,'pay_time'=>time()]);
            // 返回订单信息
            return $this->renderSuccess('', [
                'order_id' => $order_id,   // 订单号
            ]);
        } catch (\Exception $e) {
            return $this->renderError($e->getMessage());
        }
    }
}